<template>
  <div class="p-2" @click="menuHide">
    <el-row :gutter="20">
      <el-col :lg="4" :xs="24" style="">
        <el-card shadow="hover">
          <el-tree
            class="mt-2"
            ref="deptTreeRef"
            node-key="id"
            :data="groupOptions"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            default-expand-all
            @node-contextmenu.prevent="openContextMenu"
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      <el-col :lg="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div class="search" v-show="showSearch">
            <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
              <el-form-item label="关键字" prop="keyword">
                <el-input v-model="queryParams.keyword" placeholder="请输入姓名或学号" clearable style="width: 200px" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="所属班级" prop="ancestors" label-width="108px">
                <class-tree v-model="queryParams.classId" gradeDisabled />
                <!-- <el-autocomplete
                  v-model="queryParams.className"
                  :fetch-suggestions="searchClassInfo"
                  :trigger-on-focus="false"
                  placeholder="请选择班级"
                  clearable
                  @select="((e) => { queryParams.classId = e.id;  queryParams.className = e.className; })"
                >
                  <template #default="{ item }">
                    <div class="value">{{ item.className }}</div>
                  </template>
                </el-autocomplete> -->
              </el-form-item>
              <!-- <el-form-item label="人员类型" prop="groupName">
                <el-select v-model="queryParams.accommodationType" placeholder="请选择" clearable v-if="groupType === '1'">
                  <el-option v-for="dict in student_accommodation_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
                <el-select v-model="queryParams.postId" placeholder="请选择" clearable v-if="groupType === '2'">
                  <el-option v-for="dict in school_post" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </transition>

        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <!-- <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['attendance:group:add']">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['attendance:group:edit']"
                  >修改</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['attendance:group:remove']"
                  >删除</el-button
                >
              </el-col> -->
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['attendance:group:export']">导出</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table height="calc(100vh - 370px)" v-loading="loading" :data="groupList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="姓名" align="center" prop="studentName" />
            <!-- <el-table-column label="人员类型" align="center" :prop="groupType === '1' ? 'accommodationType':'postIds'">
              <template #default="scope">
                <dict-tag v-if="groupType === '1'" :options="student_accommodation_type" :value="scope.row.accommodationType" />
                <dict-tag v-if="groupType === '2'" :options="school_post" :value="scope.row.postIds" />
              </template>
            </el-table-column> -->
            <el-table-column label="学号" align="center" prop="studentNo" />
            <el-table-column label="班级" align="center" prop="className" />
            <el-table-column label="所属考勤组" align="center" prop="groupName" />
            <el-table-column label="考勤规则" align="center" prop="ruleName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="修改" placement="top" v-hasPermi="['dormitory:student:edit']">
                  <el-button link type="primary" icon="Edit" @click="handleUpdateGroup(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top" v-hasPermi="['dormitory:student:remove']">
                  <el-button link type="primary" icon="Delete" @click="handleRemoveFromGroup(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>
    <div v-show="showMenu" class="custom-menu">
      <ul>
        <li @click="menuItemAdd" v-hasPermi="['dormitory:rule:add']">新增考勤组</li>
        <li @click="menuItemUpdate" v-hasPermi="['dormitory:rule:edit']">编辑</li>
        <li @click="menuItemLink" v-hasPermi="['dormitory:rule:relevance']">关联考勤人员</li>
        <li @click="menuItemDelete" v-show="!currentNodeData.children" v-hasPermi="['dormitory:rule:remove']">删除</li>
        <li @click="menuHide">取消</li>
      </ul>
    </div>
    <!-- 添加或修改考勤分组对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="750px" append-to-body>
      <el-form ref="groupFormRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入分组名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="groupLinkDialog.title" v-model="groupLinkDialog.visible" width="750px" append-to-body>
      <el-form ref="groupLinkFormRef" :model="linkForm" label-width="110px">
        <el-form-item label="参与考勤人员" prop="groupMember" required>
          <tree-transfer
            ref="treeTransferRef"
            :nodeKey="'id'"
            :fromData="fromData"
            :toData="toData"
            :defaultProps="transferProps"
            :leftTit="'可选菜单'"
            :rightTit="'已选菜单'"
            @checkVal="checkVal"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitLinkForm">确 定</el-button>
          <el-button @click="cancelLink">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="crewLinkDialog.title" v-model="crewLinkDialog.visible" width="750px" append-to-body>
      <el-form ref="crewLinkFormRef" :model="linkForm" label-width="110px">
        <el-form-item label="考勤分组" prop="groupId" required>
          <el-tree-select
            v-model="linkForm.groupId"
            :data="formGroupOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            default-expand-all
            value-key="deptId"
            placeholder="请选择考勤分组"
            check-strictly
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitLinkForm">确 定</el-button>
          <el-button @click="cancel2">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Group" lang="ts">
import { getGroup, delGroup, addGroup, updateGroup, groupTreeSelect } from '@/api/attendance/setting/group';
import { GroupVO, GroupQuery, GroupForm } from '@/api/attendance/setting/group/types';
import { DeptVO } from '@/api/system/dept/types';
import { listClassInfo } from '@/api/office/class';
import api from '@/api/system/user';
import {
  studentTree,
  attendanceGroupPage as attendanceGroupStudentPage,
  editAttendanceGroup as editStudentAttendanceGroup,
  removeAttendanceGroup as removeStudentAttendanceGroup
} from '@/api/office/student';
import {
  attendanceGroupPage as attendanceGroupStaffPage,
  editAttendanceGroup as editStaffAttendanceGroup,
  removeAttendanceGroup as removeStaffAttendanceGroup
} from '@/api/office/staff';

import {
  listMemberAttendanceGroup,
  getMemberAttendanceGroup,
  delMemberAttendanceGroup,
  addMemberAttendanceGroup,
  updateMemberAttendanceGroup
} from '@/api/attendance/memberAttendanceGroup';
import { MemberAttendanceGroupVO, MemberAttendanceGroupQuery, MemberAttendanceGroupForm } from '@/api/attendance/memberAttendanceGroup/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { student_accommodation_type, school_post } = toRefs<any>(proxy?.useDict('student_accommodation_type', 'school_post'));
const groupList = ref<any[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const groupOptions = ref<any[]>([]);
const formGroupOptions = ref<any[]>([]);
const queryFormRef = ref<ElFormInstance>();
const groupFormRef = ref<ElFormInstance>();
const groupLinkFormRef = ref<ElFormInstance>();
const crewLinkFormRef = ref<ElFormInstance>();
const groupType = ref('1');
const deptOptions = ref<DeptVO[]>([]);
const showMenu = ref(false);
const currentNodeData = ref<any>({});
const treeTransferRef = ref(); // 树形穿梭框
const fromData = ref([]); // 树形数据
const toData = ref([]); // 选中的ids数据
const transferProps = ref({ value: 'id', label: 'label', children: 'children', disabled: 'disabled', pid: 'parentId' });
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const groupLinkDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const crewLinkDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: GroupForm = {
  groupId: undefined,
  parentId: '0',
  ancestors: undefined,
  groupName: undefined,
  groupType: undefined,
  orderNum: undefined,
  status: undefined
};
const data = reactive<PageData<GroupForm, GroupQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    parentId: undefined,
    ancestors: undefined,
    groupName: undefined,
    groupType: undefined,
    orderNum: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    groupId: [{ required: true, message: '分组id不能为空', trigger: 'blur' }],
    parentId: [{ required: true, message: '父分组id不能为空', trigger: 'blur' }],
    ancestors: [{ required: true, message: '祖级列表不能为空', trigger: 'blur' }],
    groupName: [{ required: true, message: '分组名称不能为空', trigger: 'blur' }],
    groupType: [{ required: true, message: '分组类型：1、学生考勤；2、教职工考勤不能为空', trigger: 'change' }],
    orderNum: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const linkForm = ref<any>({});

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 节点单击事件 */
const handleNodeClick = (data: any) => {
  menuHide();
  form.value.parentId = data.id;
  getGroup(data.id).then((resp) => {
    groupType.value = resp.data.groupType;
    const groupIds = [...resp.data.children];
    groupIds.push(data.id);
    queryParams.value.attendanceGroupIds = groupIds;
    handleQuery();
  });
};

/** 查询部门下拉树结构 */
const getGroupTree = async () => {
  const res = await groupTreeSelect({ groupType: '0,3' });
  groupOptions.value = res.data;
};

const searchClassInfo = (queryString, cb) => {
  listClassInfo({ className: queryString }).then((response) => {
    cb(response.rows);
  });
};

/** 查询部门下拉树结构 */
const getDeptTree = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};

const openContextMenu = (event: any, nodeData: any) => {
  // 设置菜单的位置
  const menu = proxy?.$el.querySelector('.custom-menu');
  const clickX = event.clientX;
  const clickY = event.clientY;
  menu.style.left = clickX + 10 + 'px';
  menu.style.top = clickY + 'px';
  currentNodeData.value = nodeData;
  showMenu.value = true;
};

const menuItemAdd = (option: any) => {
  showMenu.value = false;
  handleAdd();
};

const menuItemUpdate = (option: any) => {
  showMenu.value = false;
  handleUpdate(currentNodeData.value);
};

const menuItemLink = (option: any) => {
  showMenu.value = false;
  handleAddLink(currentNodeData.value);
};

const menuItemDelete = async () => {
  showMenu.value = false;
  await handleDelete(currentNodeData.value);
};

const menuHide = (option: any) => {
  showMenu.value = false;
};

/** 查询考勤分组列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMemberAttendanceGroup(queryParams.value);
  groupList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 取消按钮 */
const cancel2 = () => {
  reset();
  crewLinkDialog.visible = false;
};

const cancelLink = () => {
  reset();
  groupLinkDialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  fromData.value = [];
  toData.value = [];
  linkForm.value = {};
  treeTransferRef.value?.clearData();
  groupFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.classId = undefined;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: GroupVO[]) => {
  ids.value = selection.map((item) => item.groupId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const loadFromData = async () => {
  const res = await studentTree({ type: 2 });
  fromData.value = res.data;
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  form.value.parentId = currentNodeData.value.id;
  dialog.visible = true;
  dialog.title = '添加考勤分组';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: GroupVO) => {
  reset();
  const _groupId = row?.id || ids.value[0];
  const res = await getGroup(_groupId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改考勤分组';
};

const handleUpdateGroup = async (row?: any) => {
  reset();
  linkForm.value.studentIds = [row.id];
  const res = await groupTreeSelect({ groupType: 3 });
  formGroupOptions.value = res.data;
  crewLinkDialog.visible = true;
  crewLinkDialog.title = '修改考勤分组';
};

const handleAddLink = async (row: any) => {
  reset();
  await loadFromData();
  treeTransferRef.value?.initData();
  linkForm.value.groupId = row.id;
  groupLinkDialog.visible = true;
  groupLinkDialog.title = '关联考勤人员';
};

/** 提交按钮 */
const submitForm = () => {
  groupFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.groupId) {
        await updateGroup(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addGroup(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getGroupTree();
      await getList();
    }
  });
};

const submitLinkForm = async () => {
  if (!linkForm.value.groupId) return;
  buttonLoading.value = true;
  await updateMemberAttendanceGroup(linkForm.value).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess('修改成功');
  groupLinkDialog.visible = false;
  crewLinkDialog.visible = false;
  await getList();
};

/** 删除按钮操作 */
const handleDelete = async (row: GroupVO) => {
  const _groupIds = row.id;
  let tipText = '是否确认删除选中的数据？';
  if (row?.id) {
    tipText = '是否确认删除"' + row.label + '"的数据项？';
  }
  await proxy?.$modal.confirm(tipText).finally(() => (loading.value = false));
  await delGroup(_groupIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getGroupTree();
  await getList();
};

const handleRemoveFromGroup = async (row: any) => {
  const _ids = row.id;
  let tipText = '是否确认删除选中的数据？';
  if (row?.id) {
    tipText = '是否确认删除"' + row.studentName + '"的数据项？';
  }
  await proxy?.$modal.confirm(tipText).finally(() => (loading.value = false));
  await delMemberAttendanceGroup(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getGroupTree();
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'attendance/group/export',
    {
      ...queryParams.value
    },
    `group_${new Date().getTime()}.xlsx`
  );
};

/**
 * 将选中菜单存入表单
 * @param val 子组件穿梭框返回
 */
const checkVal = (val: any) => {
  const arr = [];
  for (const i of val) {
    if (!i.children) {
      arr.push(i.id);
    }
  }
  linkForm.value.studentIds = arr;
};

onMounted(() => {
  getDeptTree();
  getGroupTree();
  getList();
});
</script>
<style lang="scss" scoped>
@import '@/assets/styles/variables.module.scss';
.custom-menu {
  position: fixed;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
  z-index: 1000;
}

.custom-menu ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.custom-menu ul li {
  padding: 8px 20px;
  cursor: pointer;
  font-size: 13px;
  color: $blue;
}

.custom-menu ul li:hover {
  background-color: #eee;
}
.ss-tabs {
  background-color: #fff;
}
</style>
